package mylibrary.activeMQ;

import java.util.Date;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;

public class MessagePublisher implements Runnable{

	private String url;
	private String user;
	private String password;
	private String topicName;
	
	public MessagePublisher(String topicName, String url, String user, String password) {
		this.topicName = topicName;
		this.user = user;
		this.url = url;
		this.password = password;
	}
	
	public void run() {
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);
		
		Session session = null;
		MessageProducer sendPublisher;
		Connection connection = null;
		
		int messageCount = 0;
		
		try {
			
			connection = factory.createConnection();
			connection.start();
			
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			Topic topic = session.createTopic(this.topicName);
			sendPublisher = session.createProducer(topic);
			
			while(true) {
				String text = new Date() + "It is sending number " + messageCount + "message";
				sendPublisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
				sendPublisher.send(session.createTextMessage(text));
				
				if((++messageCount) == 10) {
					break;
				}
				
				Thread.sleep(1000);
			}
 			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getTopicName() {
		return topicName;
	}

	public void setTopicName(String topicName) {
		this.topicName = topicName;
	}
	
	
}
